//
//  XLFormBaseCell.m
//  XLForm ( https://github.com/xmartlabs/XLForm )
//
//  Copyright (c) 2015 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#import "XLFormBaseCell.h"
#import <Masonry/Masonry.h>
#import <BCComConfigKit/BCComConfig.h>


@interface XLFormBaseCell()
@property (strong, nonatomic, readwrite) UILabel *splitLineLb;
/** 红色星号，表示必填 */
@property (nonatomic, strong, readwrite) UILabel *asteriskLab;
/// 圆角view，默认nil，访问属性自动生成
@property (nonatomic, strong, nullable, readwrite) UIView *cornerView;
/// 自定义指示器view，默认nil，访问属性自动生成
@property (nonatomic, strong, nullable, readwrite) UIImageView *indicatorView;
@end

@implementation XLFormBaseCell
@synthesize bottomLineInset =_bottomLineInset;
#pragma mark - system
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self configure];
    }
    return self;
}
- (void)awakeFromNib {
    [super awakeFromNib];
    [self configure];
}

#pragma mark - getter
-(UILabel *)splitLineLb {
    if (!_splitLineLb) {
        _splitLineLb = [[UILabel alloc] init];
        _splitLineLb.backgroundColor = BCComConfig.config.splitColor;
    }
    return _splitLineLb;
}
-(UIView *)cornerView {
    if (!_cornerView) {
        _cornerView = [[UIView alloc] init];
        _cornerView.backgroundColor = UIColor.whiteColor;
    }
    return _cornerView;
}
- (UIImageView *)indicatorView {
    if (!_indicatorView) {
        _indicatorView = [[UIImageView alloc] initWithImage:XZHFormImageNamed(@"forwardarrow.png")];
    }
    return _indicatorView;
}

#pragma mark - public
-(XLFormViewController *)formViewController
{
    id responder = self;
    while (responder){
        if ([responder isKindOfClass:[XLFormViewController class]]){
            return responder;
        }
        responder = [responder nextResponder];
    }
    return nil;
}

#pragma mark - Navigation Between Fields
-(UIView *)inputAccessoryView
{
    UIView * inputAccessoryView = [self.formViewController inputAccessoryViewForRowDescriptor:self.rowDescriptor];
    if (inputAccessoryView){
        return inputAccessoryView;
    }
    return [super inputAccessoryView];
}
-(BOOL)becomeFirstResponder
{
    BOOL result = [super becomeFirstResponder];
    if (result){
        [self.formViewController beginEditing:self.rowDescriptor];
    }
    return result;
}

-(BOOL)resignFirstResponder
{
    BOOL result = [super resignFirstResponder];
    if (result){
        [self.formViewController endEditing:self.rowDescriptor];
    }
    return result;
}

#pragma mark - KVC
-(void)setValue:(id)value forUndefinedKey:(NSString *)key {
    // configureCellAtCreationTime 调用self.cell setValue:forKeyPath:的时候，具体的cell,可能没有这个属性，这里增加保护
}

#pragma mark - XLFormDescriptorCell
- (void)configure {
    _bottomLineInset = UIEdgeInsetsMake(0, 15, 0, 0);
    //分割线
    BOOL showBottomSplit = [self showBottomSplitLine];
    if (showBottomSplit) {
        //显示分割线
        if (!self.splitLineLb.superview) {
            [self addSubview:self.splitLineLb];
            [self.splitLineLb mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(self).mas_offset(self.bottomLineInset.left);
                make.right.mas_equalTo(self).mas_offset(0-self.bottomLineInset.right);
                make.height.mas_equalTo(0.5);
                make.bottom.mas_equalTo(self);
            }];
        }
    } else {
        //不显示分割线
        if (_splitLineLb.superview) {
            [_splitLineLb removeFromSuperview];
        }
    }
}

- (void)update {
    self.textLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
    self.detailTextLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
    self.textLabel.textColor  = self.rowDescriptor.isDisabled ? [UIColor grayColor] : [UIColor blackColor];
    //背景色
    if (self.rowDescriptor.bgColor) {
        self.backgroundColor = self.rowDescriptor.bgColor;
    }
    if (self.rowDescriptor.contentBgColor) {
        self.contentView.backgroundColor = self.rowDescriptor.contentBgColor;
    }
    //指示器
    if (self.rowDescriptor.indicatorImage != nil) {
        if (!self->_indicatorView.superview) {
            [self.contentView addSubview:self.indicatorView];
            self.indicatorView.image = self.rowDescriptor.indicatorImage;
            [self.indicatorView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.right.mas_equalTo(-14);
                make.width.mas_equalTo(self.rowDescriptor.indicatorImage.size.width);
                make.height.mas_equalTo(self.rowDescriptor.indicatorImage.size.height);
                make.centerY.offset(0);
            }];
        }
    }
    else {
        [self->_indicatorView removeFromSuperview];
        self->_indicatorView = nil;
    }
    //圆角
    if (self.rowDescriptor.cornerRadius>0) {
        if (!self->_cornerView.superview) {
            [self.contentView insertSubview:self.cornerView atIndex:0];
            self.cornerView.layer.cornerRadius = self.rowDescriptor.cornerRadius;
            self.cornerView.layer.borderColor = self.rowDescriptor.borderColor.CGColor;
            self.cornerView.layer.borderWidth = self.rowDescriptor.borderWidth;
            [self.cornerView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(self.rowDescriptor.cornerInsets.left);
                make.right.mas_equalTo(-self.rowDescriptor.cornerInsets.right);
                make.top.mas_equalTo(self.rowDescriptor.cornerInsets.top);
                make.bottom.mas_equalTo(-self.rowDescriptor.cornerInsets.bottom);
            }];
            if (self->_indicatorView != nil) {
                [self->_indicatorView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.right.mas_equalTo(-14 - self.rowDescriptor.cornerInsets.right);
                }];
            }
        }
    }
    else {
        [self->_cornerView removeFromSuperview];
        self->_cornerView = nil;
    }
    //更新分割线
    if (_splitLineLb.superview) {
        _splitLineLb.hidden = false;
        [_splitLineLb mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self).mas_offset(self.bottomLineInset.left);
            make.right.mas_equalTo(self).mas_offset(0-self.bottomLineInset.right);
        }];
        if (self.rowDescriptor.splitLeft>0) {
            //更新分割线的left
            [_splitLineLb mas_updateConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(self).mas_offset(self.rowDescriptor.splitLeft);
            }];
        }
        else if (self.rowDescriptor.splitLeft<0) {
            //不显示分割线
            _splitLineLb.hidden = true;
        }
    }
}

-(void)highlight {
}

-(void)unhighlight {
}

-(void)formDescriptorDidDone {
}

-(BOOL)formDescriptorCellCanBecomeFirstResponder {
    return NO;
}
-(BOOL)formDescriptorCellShowInputAccessoryView {
    return YES;
}
-(BOOL)showBottomSplitLine {
    return NO;
}

#pragma mark - getter
- (UILabel *)asteriskLab {
    if (!_asteriskLab) {
        _asteriskLab = [[UILabel alloc] init];
        _asteriskLab.translatesAutoresizingMaskIntoConstraints = NO;
        _asteriskLab.font = BCComConfig.config.bcFont(15);
        _asteriskLab.textColor = [UIColor bc_colorWithRGBString:@"FF5856"];
        _asteriskLab.text = @"*";
    }
    return _asteriskLab;
}
@end
